//
//  KSCountButton.swift
//  PigManager
//
//  Created by 邱仙凯 on 2020/6/5.
//  Copyright © 2020 Much. All rights reserved.
//

import UIKit

class KSCountButton: UIView,UITextFieldDelegate {
  
    var valueChanged:((Int,Bool)->())?
    
    /** *  晃动动画，default is NO 不开启 */
    var shakeAnimation = false
    
    /** *  '减' 按钮隐藏功能，default is NO 不隐藏 */
    var decreaseHide = false {
        didSet {
           
                if decreaseHide {
                    if intTran(self.inputTextField.text) <= self.minValue {
                        self.inputTextField.isHidden = true
                        self.inputTextField.text = "\(self.minValue - 1)"
            
                        self.decreaseBtn.frame = CGRect(x:self.frame.width-self.frame.height,y: 0,width: self.frame.height,height: self.frame.height)
                    }
                    self.backgroundColor = .clear
                }
                else {
                    self.decreaseBtn.frame = CGRect(x:0,y: 0,width: self.frame.height,height: self.frame.height)
                }
        }
    }
    
    /** *  是否可以键盘输入，default is YES */
    var editing = true {
        didSet {
             self.inputTextField.isEnabled = editing
        }
    }
 
  
    /** *  长按加减按钮时间间隔，Default is CGFLOAT_MAX 默认功能关闭，若需要开启，设置一个不为 CGFLOAT_MAX 的值即可 */
    var longPressSpaceTime = CGFloat.greatestFiniteMagnitude
    
     /** *  当前值 */
    var currentNumber: Int {
        set {
           
            if self.decreaseHide && newValue < self.minValue {
                self.inputTextField.isHidden = true
                    self.inputTextField.alpha = 0.0
            
                self.decreaseBtn.frame = CGRect(x:self.frame.width - self.frame.height,y: 0,width: self.frame.height, height:self.frame.height)
                }
                else
                {
                    self.inputTextField.isHidden = false
                    self.inputTextField.alpha = 1.0
            
                    self.decreaseBtn.frame = CGRect(x:0,y: 0,width: self.frame.height,height: self.frame.height)
                }
            
            self.inputTextField.text = "\(currentNumber)"
            self.checkInputAndUpdate()
            
             
        }
        get {
            intTran(self.inputTextField.text)
        }
 
    }
    
        /** * 跨度  幅度 */
    var fuduNumber:Int?
  
    /** *  输入框文字字体 default is [UIFont fontWithName:@"Arial" size:13] */
    var inputFont = UIFont.systemFont(ofSize: 13) {
        didSet {
            self.inputTextField.font = inputFont
        }
    }

    /** *  输入框文字颜色 default is [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1] */
    var inputColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1) {
        didSet {
            self.inputTextField.textColor = inputColor
        }
    }
     
    var boarderColor:UIColor? {
        didSet {
            self.increaseBtn.layer.borderColor = borderColor!.cgColor
            self.increaseBtn.layer.borderWidth = 1.0/UIScreen.main.scale
            
            self.decreaseBtn.layer.borderColor = borderColor!.cgColor
                self.decreaseBtn.layer.borderWidth = 1.0/UIScreen.main.scale
        }
    }
    
  
    /** *  最小值, default is 1 */
    var minValue = 1 {
        didSet {
             
              
            self.inputTextField.text = "\(minValue)"
            
            // 为了触发didset方法
            let temp = self.decreaseHide
            self.decreaseHide = temp
            
             
        }
    }

    /** *  最大值，default 无上限 */
    var maxValue = Int.max
 
 
    /** *  按钮字体 default is [UIFont fontWithName:@"Arial" size:15] */
    var buttonTitleFont = UIFont.systemFont(ofSize: 15) {
        didSet {
            self.increaseBtn.titleLabel?.font = buttonTitleFont
            self.decreaseBtn.titleLabel?.font = buttonTitleFont
        }
    }

    /** *  '加' 按钮图片 */
    var increaseImage:UIImage? {
        didSet {
            self.increaseBtn.setBackgroundImage(increaseImage, for: .normal)
            self.increaseTitle = ""
        }
    }
 
    

    /** *  '减' 按钮图片 */
    var decreaseImage:UIImage? {
        didSet {
            self.decreaseBtn.setBackgroundImage(decreaseImage, for: .normal)
            self.decreaseTitle = ""
        }
    }

    /** *  '加' 按钮标题 default is '+' */
    var increaseTitle = "+" {
        didSet {
            self.increaseBtn.setTitle(increaseTitle, for: .normal)
        }
    }

    /** *  '减' 按钮标题 default is '-' */
    var decreaseTitle = "-" {
        didSet {
            self.decreaseBtn.setTitle(decreaseTitle, for: .normal)
        }
    }
     

 
    
    /** * 减按钮 */
   lazy var  decreaseBtn:UIButton = {
        let btn = UIButton(type: .system)
        btn.titleLabel?.font = self.buttonTitleFont
        btn.setTitleColor(.gray, for: .normal)
        btn.addTarget(self, action: #selector(touchDown(sender:)), for: .touchDown)
        btn.addTarget(self, action: #selector(touchUp(sender:)), for: .touchUpInside)
         btn.addTarget(self, action: #selector(touchUp(sender:)), for: .touchUpOutside)
         btn.addTarget(self, action: #selector(touchUp(sender:)), for: .touchCancel)
        self.addSubview(btn)
       return btn
    }()
    /** * 加按钮 */
      lazy var  increaseBtn:UIButton = {
           let btn = UIButton(type: .system)
           btn.titleLabel?.font = self.buttonTitleFont
           btn.setTitleColor(.gray, for: .normal)
           btn.addTarget(self, action: #selector(touchDown(sender:)), for: .touchDown)
           btn.addTarget(self, action: #selector(touchUp(sender:)), for: .touchUpInside)
            btn.addTarget(self, action: #selector(touchUp(sender:)), for: .touchUpOutside)
            btn.addTarget(self, action: #selector(touchUp(sender:)), for: .touchCancel)
           self.addSubview(btn)
          return btn
       }()
 
  

    /** * 快速加减定时器 */
    private var timer:Timer?
    
    /** * 数量展示/输入框 */
    private lazy var inputTextField:UITextField = {
        let field = UITextField()
        field.delegate = self
        field.textAlignment = .center
        field.keyboardType = .numberPad
        field.font = self.inputFont
        field.textColor = self.inputColor
        field.text = "\(self.minValue)"
        self.addSubview(field)
        return field
    }()
    
 

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUI()
    }
//    override class func awakeFromNib() {
//        super.awakeFromNib()
//        self.setupUI()
//    }
//
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    
    func setupUI () {
          self.minValue = 1
           self.maxValue = Int.max
           
           self.inputFont = UIFont.systemFont(ofSize: 13)
           self.inputColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
           
           self.buttonTitleFont = UIFont.systemFont(ofSize: 15)
           self.increaseTitle = "+"
           self.decreaseTitle = "-"
           
           self.longPressSpaceTime = CGFloat.greatestFiniteMagnitude
           self.decreaseHide = false
           self.shakeAnimation = false
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.inputTextField.frame = CGRect(x:self.frame.height,y:0,width: self.frame.width - self.frame.height * 2,height:self.frame.height)
        self.increaseBtn.frame = CGRect(x:self.frame.width - self.frame.height, y: 0, width: self.frame.height, height: self.frame.height)
        if self.decreaseHide && intTran(self.inputTextField.text) < self.minValue {
            self.decreaseBtn.frame = CGRect(x:self.frame.width - self.frame.height, y: 0, width: self.frame.height, height: self.frame.height)
            self.decreaseBtn.alpha = 0.0
        } else {
            self.decreaseBtn.frame = CGRect(x:0, y: 0, width: self.frame.height, height: self.frame.height)
        }
        
    }
    @objc func touchUp(sender:UIButton) {
        if self.timer!.isValid {
            self.timer?.invalidate()
            self.timer = nil
        }
    }
    
    @objc func touchDown(sender:UIButton) {
        self.inputTextField.resignFirstResponder()
        if sender == self.increaseBtn {
            self.timer = Timer(timeInterval: TimeInterval(self.longPressSpaceTime), target: self, selector: #selector(valueIncrease), userInfo: nil, repeats: true)
            
        } else {
            self.timer = Timer(timeInterval: TimeInterval(self.longPressSpaceTime), target: self, selector: #selector(valueDecrease), userInfo: nil, repeats: true)
        }
        RunLoop.current.add(self.timer!, forMode: .common)
        self.timer!.fire()
  
    }
    
    @objc func valueIncrease() {
        self.checkInputAndUpdate()
    
        if self.fuduNumber.isNone {
              self.fuduNumber = 1
          }
    
        let tempValue = intTran(self.inputTextField.text) + self.fuduNumber.intWrap
        if tempValue <= self.maxValue {
            // 如果原来是设置的'-'按钮是隐藏的，需要滚出来
            if self.decreaseHide && tempValue == self.minValue
            {
                // 滚动动画
                self.rotationAnimationMethod()
                UIView.animate(withDuration: 0.3, animations: {
                    self.decreaseBtn.frame = CGRect(x:0,y: 0,width: self.frame.height,height: self.frame.height)
                    self.decreaseBtn.alpha = 1
                }) { (_) in
                    self.inputTextField.isHidden = false
                    self.inputTextField.alpha = 1
                }
             
            }
            self.inputTextField.text = "\(tempValue)"
            self .callback(isIncrease: true)
    
        }
        else
        {
            if (self.shakeAnimation)
            {
                self.shakeAnimationMethod()
            }
        }
    }
    
    
   @objc func valueDecrease() {
        self.checkInputAndUpdate()
    
         if self.fuduNumber.isNone {
             self.fuduNumber = 1
         }
      let tempValue = intTran(self.inputTextField.text) - self.fuduNumber.intWrap
    
        if tempValue >= self.minValue {
            self.inputTextField.isHidden = false
            self.inputTextField.text = "\(tempValue)"
            self .callback(isIncrease: false)
        }
        else
        {
            // 如果设置了最小值就隐藏的功能，当减到最小时，要滚回去
            if self.decreaseHide && tempValue < self.minValue {
                self.rotationAnimationMethod()
                
            
             UIView.animate(withDuration: 0.3, animations: {
                  self.decreaseBtn.alpha = 0.0
                self.decreaseBtn.frame = CGRect(x:self.frame.width - self.frame.height,y: 0,width: self.frame.height,height: self.frame.height)
             }) { (_) in
                 
             }
                 
    
                self.inputTextField.isHidden = true
                self.inputTextField.text = "\(self.minValue-1)"
                self .callback(isIncrease: false)
    
                return
            }
            if (self.shakeAnimation)
            {
                self.shakeAnimationMethod()
            }
        }
    }
    
    
     
        
        func checkInputAndUpdate() {
 
            if !self.inputTextField.text.unwrap.isEmpty ||
                 intTran(self.inputTextField.text) < self.minValue {
                self.inputTextField.text = self.decreaseHide ? "\(self.minValue - 1)" : "\(self.minValue)"
            } else if  intTran(self.inputTextField.text) > self.maxValue {
                self.inputTextField.text = "\(self.minValue)"
            }
        }
    
    func rotationAnimationMethod() {
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotationAnimation.toValue = Double.pi * 2
        rotationAnimation.duration = 0.3
        rotationAnimation.fillMode = CAMediaTimingFillMode.forwards
        rotationAnimation.isRemovedOnCompletion = false
        self.decreaseBtn.layer.add(rotationAnimation, forKey: nil)
    }
    
    
    func shakeAnimationMethod() {
        let tempPositionX = self.layer.position.x
        let shakeAnimation = CAKeyframeAnimation(keyPath: "position.x")
        shakeAnimation.values = [tempPositionX - 10,tempPositionX,tempPositionX + 10]
        shakeAnimation.repeatCount = 3
        shakeAnimation.duration = 0.07
        shakeAnimation.autoreverses = true
        self.layer.add(shakeAnimation, forKey: nil)
    }
    

    func callback(isIncrease:Bool) {
        if let clo = self.valueChanged {
            clo(intTran(self.inputTextField.text),isIncrease)
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.checkInputAndUpdate()
        self.callback(isIncrease: false)
    }
  
        
}


